package com.jinzhi.jzapi.training.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.training.pojo.ApplicationRecordVo;
import com.jinzhi.jzapi.training.pojo.RecruitmentNewsVo;
import com.jinzhi.jzweb.domain.ApplicationRecordDO;
import com.jinzhi.jzweb.domain.OrganizationNewsDO;
import com.jinzhi.jzweb.domain.RecruitmentNewsDO;
import com.jinzhi.jzweb.domain.ResumesDO;
import com.jinzhi.jzweb.service.ApplicationRecordService;
import com.jinzhi.jzweb.service.OrganizationNewsService;
import com.jinzhi.jzweb.service.RecruitmentNewsService;
import com.jinzhi.jzweb.service.ResumesService;
import com.jinzhi.jzweb.utils.IdCardUtil;
import com.jinzhi.sys.domain.UserDO;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

@Slf4j
@RestController
@RequestMapping("/jzApi/recruitment")
public class ApiRecruitmentController extends BaseController {

    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private ResumesService resumesService;
    @Autowired
    private RecruitmentNewsService recruitmentNewsService;
    @Autowired
    private ApplicationRecordService applicationRecordService;
    @Autowired
    private DictService sysDictService;

    /** 
    * api小程序端-机构信息展示接口
    * 
    * @Description: 查看招聘公司信息;参数：机构信息id
    * @Param: [id] 
    * @return: com.jinzhi.common.utils.ApiResult<?> 
    * @Author: kl
    * @Date: 2020-04-23 
    */ 
    @GetMapping("/selCompanyInfo")
    @Log("api小程序端-机构信息展示接口")
    @ApiOperation(value = "api小程序端-机构信息展示接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selCompanyInfo(String id) {
        if(StringUtils.isBlank(id)){
            return ApiResult.lack("");//缺少参数
        }
        OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(Long.parseLong(id));
        return ApiResult.success(organizationNewsDO);
    }

    /**
    * api小程序端-查看我的简历接口
    *
    * @Description: 查看我的简历；参数：验证token
    * @Param: [token]
    * @return: com.jinzhi.common.utils.ApiResult<?>
    * @Author: kl
    * @Date: 2020-04-23
    */
    @GetMapping("/selResume")
    @Log("api小程序端-查看我的简历接口")
    @ApiOperation(value = "api小程序端-查看我的简历接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selResume(@RequestHeader(value = TOKEN_TAG, required = false) String token) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        ResumesDO resumesDO = resumesService.findOneByKv("user_id",user.getId());
        if (resumesDO != null){
            if (user.getEmail() != null){
                resumesDO.setEmail(user.getEmail());
            }
            if (user.getSex() != null){
                resumesDO.setSex(user.getSex());
            }
            if (user.getHeadPortrait() != null){
                resumesDO.setHeadPortrait(user.getHeadPortrait());
            }
            if (user.getName() != null){
                resumesDO.setUserName(user.getName());
            }
            if (user.getDateOfBirth() != null){
                resumesDO.setDateOfBirth(user.getDateOfBirth());
            }
            if (user.getMobile() != null){
                resumesDO.setMobile(user.getMobile());
            }
        }


        return ApiResult.success(resumesDO);
    }

    /** 
    * api小程序端-提交和修改我的简历接口
    * 
    * @Description: 提交和修改我的简历;参数：验证token，期望职业，期望月薪，籍贯，毕业院校，工作年限，教育经历，工作经验，自我评价
    * @Param: [token, desiredOccupation, expectedSalary, nativePlace, graduatedFrom, workYears, educationExperience, workExperience, selfEvaluation] 
    * @return: com.jinzhi.common.utils.ApiResult<?> 
    * @Author: kl
    * @Date: 2020-04-23
    */ 
    @PostMapping("/updResume")
    @Log("api小程序端-提交和修改我的简历接口")
    @ApiOperation(value = "api小程序端-提交和修改我的简历接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> updResume(@RequestHeader(value = TOKEN_TAG, required = false) String token,String workYears ,String nativePlace ,String graduatedFrom,
                                  String desiredOccupation,String expectedSalary,String applyState, String jobAddress,
                                      String isPush ,String jobNature ,String skills, String selfEvaluation, String educationExperience,
                                  String workExperience, String project ,String certificate) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        boolean b;
        ResumesDO resumesDO = resumesService.findOneByKv("user_id",user.getId());
        if(resumesDO != null){
            resumesDO.setWorkExperience(workExperience);//工作经验
            resumesDO.setWorkYears(workYears);//工作年限
            resumesDO.setNativePlace(nativePlace);//籍贯
            resumesDO.setGraduatedFrom(graduatedFrom);//毕业院校
            resumesDO.setDesiredOccupation(desiredOccupation);//期望职业
            resumesDO.setExpectedSalary(expectedSalary);//期望月薪
            resumesDO.setSelfEvaluation(selfEvaluation);//自我评价
            resumesDO.setEducationExperience(educationExperience);//教育经历
            resumesDO.setApplyState(Integer.parseInt(applyState));
            resumesDO.setJobAddress(jobAddress);
            resumesDO.setIsPush(Integer.parseInt(isPush));
            resumesDO.setJobNature(Integer.parseInt(jobNature));
            resumesDO.setSkills(skills);
            resumesDO.setProject(project);
            resumesDO.setCertificate(certificate);
            b = resumesService.updateById(resumesDO);
        }else{
            ResumesDO resumesDO1 = new ResumesDO();
            resumesDO1.setUserId(user.getId());//用户id
            resumesDO1.setWorkExperience(workExperience);//工作经验
            resumesDO1.setWorkYears(workYears);//工作年限
            resumesDO1.setNativePlace(nativePlace);//籍贯
            resumesDO1.setGraduatedFrom(graduatedFrom);//毕业院校
            resumesDO1.setDesiredOccupation(desiredOccupation);//期望职业
            resumesDO1.setExpectedSalary(expectedSalary);//期望月薪
            resumesDO1.setSelfEvaluation(selfEvaluation);//自我评价
            resumesDO1.setEducationExperience(educationExperience);//教育经历
            resumesDO1.setState(0);//默认上线
            resumesDO1.setJobAddress(jobAddress);
            resumesDO1.setIsPush(Integer.parseInt(isPush));
            resumesDO1.setJobNature(Integer.parseInt(jobNature));
            resumesDO1.setApplyState(Integer.parseInt(applyState));
            resumesDO1.setSkills(skills);
            resumesDO1.setProject(project);
            resumesDO1.setCertificate(certificate);
            b = resumesService.insert(resumesDO1);
        }
        if(b){

            if (Integer.parseInt(isPush) == 1){
                //匹配该用户期望职业的招聘信息
                Wrapper<RecruitmentNewsDO> wrapper = new EntityWrapper<>();
                wrapper.like("name" , desiredOccupation);
                List<RecruitmentNewsDO> recNewsList = recruitmentNewsService.selectList(wrapper);
                if (recNewsList.size() != 0){
                    for (RecruitmentNewsDO recNews : recNewsList){
                        //自动投递简历·
                        ApplicationRecordDO appRecord = applicationRecordService.findOneByKv("rnews_id" , recNews.getId(), "user_id" , user.getId());
                        if (appRecord == null){
                            ApplicationRecordDO applicationRecord = new ApplicationRecordDO();
                            applicationRecord.setRnewsId(recNews.getId());
                            applicationRecord.setOrgId(recNews.getOrgId());
                            applicationRecord.setUserId(user.getId());
                            applicationRecord.setState(2);
                            applicationRecord.setAppTime(new Date());
                            applicationRecord.setCreaterDate(new Date());
                            applicationRecordService.insert(applicationRecord);
                        }
                    }
                }
            }

            return ApiResult.success();
        }else{
            return ApiResult.fail("提交错误");
        }
    }

    /**
     * api小程序端-招聘岗位列表接口--公开方法，不需要登录
     *
     * @Description: 招聘岗位列表接口（需分页），参数：页码，显示数，岗位名称，0热门/1最新（筛选条件）
     * @Param: [current, number, name, type]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-26
     * 前端企业发布的查询展示
     */
    @GetMapping("/selScreen")
    @Log("api小程序端-招聘岗位筛选条件接口")
    @ApiOperation(value = "api小程序端-招聘岗位筛选条件接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object selScreen() {
        Map map1 = new HashMap();
        map1.put("Type","experience");

        List<DictDO>  list=sysDictService.selectListBy(map1);
        List list1=new ArrayList();
        for(DictDO li:list){
            Map map=new HashMap();
            map.put("id",li.getId());
            map.put("name",li.getValue());
            list1.add(map);
        }
        Map map = new HashMap();

        Map map1money = new HashMap();
        map1money.put("Type","moneyList");
        List<DictDO>  listMoney=sysDictService.selectListBy(map1money);
        List list2=new ArrayList();
        for(DictDO li:listMoney){
            Map mapmoney=new HashMap();
            mapmoney.put("id",li.getId());
            mapmoney.put("name",li.getValue());
            list2.add(mapmoney);
        }
        //行业
        map.put("industryList",recruitmentNewsService.listRecru());

        map.put("experienceList",list1);
        //薪资范围
        map.put("moneyList",list2);

        return ApiResult.success(map);
    }

    /**
     * api小程序端-招聘岗位列表接口--公开方法，不需要登录
     *
     * @Description: 招聘岗位列表接口（需分页），参数：页码，显示数，岗位名称，0热门/1最新（筛选条件）
     * @Param: [current, number, name, type]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-26
     * 前端企业发布的查询展示
     */
    @GetMapping("/selJobList")
    @Log("api小程序端-招聘岗位列表接口")
    @ApiOperation(value = "api小程序端-招聘岗位列表接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selJobList(String current, String number, String name, String type,String city,String experience,String education ,String scale,String postName,String requirement) {
        if(StringUtils.isBlank(type)){
            return ApiResult.lack("");//缺少参数
        }
        //判断是否为数字
        if (!IdCardUtil.isNumeric(type)) {
            return ApiResult.format("");//格式错误
        }
        Map map = new HashMap();
        if(StringUtil.notEmpty(name)){
            map.put("name",name);
        }
        map.put("statusValue",1);
        if(StringUtil.notEmpty(city)){
            map.put("address",city);
        }

        //经验
        if(StringUtil.notEmpty(experience)){
            map.put("workExperience",experience);
        }

        //学历
        if(StringUtil.notEmpty(education)){
            map.put("education", education );
        }

        //规模
        if(StringUtil.notEmpty(scale)){
            map.put("scale", scale);
        }

        //岗位名称
        if(StringUtil.notEmpty(postName)){
            map.put("field", postName );
        }

        //薪资要求
        if(StringUtil.notEmpty(requirement)){
            map.put("salaryRange",  requirement );
        }


        Page<RecruitmentNewsVo> page = recruitmentNewsService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map,type);
        return ApiResult.success(page);
    }

    /**
    * api小程序端-招聘岗位详情接口
    *
    * @Description: 获取岗位信息详情，参数：岗位id
    * @Param: [id]
    * @return: com.jinzhi.common.utils.ApiResult<?>
    * @Author: kl
    * @Date: 2020-04-26
    */
    @GetMapping("/selJobDetails")
    @Log("api小程序端-招聘岗位详情接口")
    @ApiOperation(value = "api小程序端-招聘岗位详情接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selJobDetails(String id) {
        if(StringUtils.isBlank(id)){
            return ApiResult.lack("");//缺少参数
        }
        RecruitmentNewsDO recruitmentNews = recruitmentNewsService.selectById(Long.parseLong(id));
        recruitmentNews.setBrowseNumber(recruitmentNews.getBrowseNumber() + 1);
        boolean b = recruitmentNewsService.updateById(recruitmentNews);
        if(b){
            RecruitmentNewsDO recruitmentNewsDO = recruitmentNewsService.selJobDetails(Long.parseLong(id));
            return ApiResult.success(recruitmentNewsDO);
        }else{
            return ApiResult.fail("信息错误，请重试");
        }


    }

    /** 
    * api小程序端-个人中心-控制简历上线下线接口
    * 
    * @Description: 根据简历id，控制自己简历上线下线；参数：简历id，状态（0上线，1下线）
    * @Param: [token, id, state] 
    * @return: com.jinzhi.common.utils.ApiResult<?> 
    * @Author: kl
    * @Date: 2020-04-27 
    */ 
    @GetMapping("/updChangeState")
    @Log("api小程序端-个人中心-控制简历上线下线接口")
    @ApiOperation(value = "api小程序端-个人中心-控制简历上线下线接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> updChangeState(@RequestHeader(value = TOKEN_TAG, required = false) String token,String id,String state) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        if(StringUtils.isBlank(id)){
            return ApiResult.lack("");//缺少参数
        }
        if(StringUtils.isBlank(state)){
            return ApiResult.lack("");//缺少参数
        }
        //判断是否为数字
        if (!IdCardUtil.isNumeric(state)) {
            return ApiResult.format("");//格式错误
        }

        ResumesDO resumesDO = resumesService.selectById(Long.parseLong(id));
        if(state.equals("0")){
            resumesDO.setState(0);
        }else{
            resumesDO.setState(1);
        }
        boolean b = resumesService.updateById(resumesDO);
        if(b){
            return ApiResult.success("更改成功");
        }else{
            return ApiResult.fail("更改失败");
        }
    }

    /** 
    * api小程序端-投递简历接口
    * 
    * @Description: 用户投递简历；参数：验证token，招聘岗位id
    * @Param: [token, id] 
    * @return: com.jinzhi.common.utils.ApiResult<?> 
    * @Author: kl
    * @Date: 2020-04-27 
    */ 
    @PostMapping("/addResume")
    @Log("api小程序端-投递简历接口")
    @ApiOperation(value = "api小程序端-投递简历接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> addResume(@RequestHeader(value = TOKEN_TAG, required = false) String token,String id) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        if(StringUtils.isBlank(id)){
            return ApiResult.lack("");//缺少参数
        }

        ResumesDO resumesDO = resumesService.findOneByKv("user_id",user.getId());
        if(resumesDO != null){
            RecruitmentNewsDO recruitmentNewsDO = recruitmentNewsService.selectById(Long.parseLong(id));
            if(recruitmentNewsDO != null){
                ApplicationRecordDO applicationRecordDO = applicationRecordService.findOneByKv("user_id",user.getId(),"rnews_id",Long.parseLong(id));
                if(applicationRecordDO == null){
                    ApplicationRecordDO applicationRecordDO1 = new ApplicationRecordDO();
                    applicationRecordDO1.setUserId(user.getId());//用户id
                    applicationRecordDO1.setOrgId(recruitmentNewsDO.getOrgId());//机构id
                    applicationRecordDO1.setRnewsId(Long.parseLong(id));//招聘岗位id
                    applicationRecordDO1.setAppTime(new Date());//应聘时间
                    applicationRecordDO1.setCreaterDate(new Date());//创建时间
                    applicationRecordDO1.setState(2);//默认沟通中
                    applicationRecordDO1.setType(0);
                    boolean b = applicationRecordService.insert(applicationRecordDO1);
                    if(b){
                        recruitmentNewsDO.setAppNumber(recruitmentNewsDO.getAppNumber() + 1);
                        recruitmentNewsService.updateById(recruitmentNewsDO);

                        return ApiResult.success("投递成功，请静候佳音！");
                    }else{
                        return ApiResult.fail("投递失败，请刷新重试！");
                    }
                }else{
                    return ApiResult.fail("您已投递，请勿重复！");
                }
            }else{
                return ApiResult.fail("信息错误，请刷新重试！");
            }
        }else{
            return ApiResult.build(ApiEnumError.NORESUMES.getCode(), ApiEnumError.NORESUMES.getMsg());
        }
    }

    /** 
    * api小程序端-简历投递记录列表接口
    * 
    * @Description: 获取当前用户的简历投递记录列表信息；参数：验证token，页码，显示数，状态（0成功，1失败，2沟通中）（筛选条件) 
    * @Param: [token, current, number, state] 
    * @return: com.jinzhi.common.utils.ApiResult<?> 
    * @Author: kl
    * @Date: 2020-04-27 
    */ 
    @GetMapping("/selApplicationRecord")
    @Log("api小程序端-简历投递记录列表接口")
    @ApiOperation(value = "api小程序端-简历投递记录列表接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selApplicationRecord(@RequestHeader(value = TOKEN_TAG, required = false) String token,String current, String number,String state) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        if(StringUtils.isBlank(state)){
            return ApiResult.lack("");//缺少参数
        }
        //判断是否为数字
        if (!IdCardUtil.isNumeric(state)) {
            return ApiResult.format("");//格式错误
        }

        Map map = new HashMap();
        map.put("userId",user.getId());
        map.put("state",state);
        Page<ApplicationRecordVo> page = applicationRecordService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map);

        return ApiResult.success(page);
    }
}
